package com.xlh.wjdcserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.exception.QuestionException;
import com.property.dto.QuestionAddDTO;
import com.property.dto.QuestionDelDTO;
import com.property.dto.QuestionUpDTO;
import com.property.entity.GirlFriend;
import com.property.entity.Option;
import com.property.entity.Question;
import com.xlh.wjdcserver.mapper.OptionMapper;
import com.xlh.wjdcserver.mapper.QuestionMapper;
import com.xlh.wjdcserver.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    @Autowired
    private OptionMapper optionMapper;

    @Transactional
    @Override
    public void updateQuestion(QuestionUpDTO questionUpDTO) {
        // 先删除问卷的所有问题以及对应选项，再添加所有的题目
        // 删除问卷问题
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("q_id", questionUpDTO.getQid());
        baseMapper.delete(queryWrapper);

        // 删除问卷的所有选项
        this.deleteOptions(questionUpDTO.getQid());

        // 对题目和选项的主键设置为null
        questionUpDTO.getQuestionsAndOptions().forEach(questionAddDTO ->{
            questionAddDTO.getQuestion().setId(null);
            questionAddDTO.getOptions().forEach(option -> {
                option.setId(null);
            });
        });

        // 添加所有的题目
        this.addQuestion(questionUpDTO.getQuestionsAndOptions());
    }

    @Transactional
    @Override
    public void addQuestion(List<QuestionAddDTO> questionsAndOptions) {
        // 取出map中的所有的key，为题目
        List<Question> questionList = questionsAndOptions.stream()
                .map(questionAddDTO ->
                {
                    questionAddDTO.getQuestion().setQid(questionAddDTO.getQid());
                    return questionAddDTO.getQuestion();
                }
                )
                .collect(Collectors.toList());

        // 批量插入题目
        baseMapper.insert(questionList);

        // 取出map中所有key对应的value，为题目对应的选项
        List<Option> optionList = questionsAndOptions.stream()
                .flatMap(questionAddDTO -> {
                    Question question = questionAddDTO.getQuestion();
                    if (question.getType().equals("text"))
                    {
                        return Stream.empty();
                    }
                        questionAddDTO.getOptions().forEach(option ->
                        {
                            option.setQueId(question.getId());
                            option.setQid(question.getQid());
                        });
                    return questionAddDTO.getOptions().stream();
                }).collect(Collectors.toList());

        // 批量插入选项
        optionMapper.insert(optionList);

    }

    @Transactional
    @Override
    public void deleteQuestion(List<QuestionDelDTO> questionDelDTOS) {
        if (questionDelDTOS == null || questionDelDTOS.size() == 0)
        {
            throw new QuestionException("问卷id不能为空!");
        }
        List<String> list = questionDelDTOS.stream().map(questionDelDTO -> questionDelDTO.getQid()).toList();
        QueryWrapper<Question> questionQueryWrapper = new QueryWrapper<>();
        questionQueryWrapper.in("q_id", list);
        baseMapper.delete(questionQueryWrapper);

        this.deleteOptions(list);
    }

    @Override
    public List<Question> listQuestions(String id) {
        return baseMapper.selectList(new QueryWrapper<Question>().eq("q_id", id));
    }

    @Override
    public List<QuestionAddDTO> listQuestionsByQid(String qid) {

        QueryWrapper<QuestionAddDTO> questionQueryWrapper = new QueryWrapper<>();
        questionQueryWrapper.eq("que.delete_flag", '0');
        questionQueryWrapper.eq("que.q_id", qid);
        List<QuestionAddDTO> questionAddDTOS = baseMapper.listQuestionsByQid(questionQueryWrapper);
        Map<String, QuestionAddDTO> questionAddDTOMap = new LinkedHashMap<>();
        questionAddDTOS.forEach(questionAddDTO ->
        {
            String questionId = questionAddDTO.getQueId();
            // putIfAbsent，取出所有的题目，根据题目来去重
            questionAddDTOMap.putIfAbsent(questionId, new QuestionAddDTO());
            QuestionAddDTO questionAddDTO1 = questionAddDTOMap.get(questionId);

            // 初始化题目
            if (questionAddDTO1.getQuestion() == null)
            {
                Question question = new Question();
                question.setId(questionAddDTO.getQueId());
                question.setContent(questionAddDTO.getQueContent());
                question.setType(questionAddDTO.getQueType());
                question.setQid(questionAddDTO.getQid());
                question.setQueOrder(questionAddDTO.getQueOrder());
                questionAddDTO1.setQid(questionAddDTO.getQid());
                questionAddDTO1.setQuestion(question);
                questionAddDTO1.setOptions(new ArrayList<>());
            }

            // 初始化选项
            Option option = new Option();
            option.setId(questionAddDTO.getOptionId());
            option.setQueId(questionAddDTO.getOptionQueId());
            option.setOptionName(questionAddDTO.getOptionName());
            option.setOptionContent(questionAddDTO.getOptionContent());
            option.setQid(questionAddDTO.getQid());
            questionAddDTO1.getOptions().add(option);
        });
        return new ArrayList<>(questionAddDTOMap.values());
    }

    public <T> void deleteOptions(T qids)
    {
        if (qids == null)
        {
            throw new QuestionException("参数错误!");
        }
        // 删除问卷的所有选项
        QueryWrapper<Option> optionQueryWrapper = new QueryWrapper<>();
        if (qids instanceof List)
        {
            optionQueryWrapper.in("q_id", (List<?>) qids);
        }
        else
        {
            optionQueryWrapper.eq("q_id", qids);
        }
        optionMapper.delete(optionQueryWrapper);
    }

    public <T> void deleteQuestions(T qids)
    {
        if (qids == null)
        {
            throw new QuestionException("参数错误!");
        }
        // 删除问卷的所有选项
        QueryWrapper<Question> questionQueryWrapper = new QueryWrapper<>();
        if (qids instanceof List)
        {
            questionQueryWrapper.in("q_id", (List<?>) qids);
        }
        else
        {
            questionQueryWrapper.eq("q_id", qids);
        }
        baseMapper.delete(questionQueryWrapper);
    }
}
